using System.Collections;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Rigidbody2D))]
public class Player : MonoBehaviour
{
    [Header("Player Health")]
    [SerializeField] private int maxHealth = 5;
    [SerializeField] private Image[] hearts;
    [SerializeField] private GameObject explosionPrefab;
    [SerializeField] private GameObject gameOverUI;
    private Transform explosionPoint;

    [SerializeField] private GameObject hitEffectPrefab;

    [Header("Player movement")]
    public float moveSpeed = 5f;
    [SerializeField] private float acceleration = .1f;
    [SerializeField] private float jumpHeight = 7f;

    private Rigidbody2D rb;
    private Animator animator;
    private bool jump = true;

    [Space(10)]
    [SerializeField] private Transform shootPoint;
    [SerializeField] private float distance;
    [SerializeField] private LayerMask targetLayer;
    private LineRenderer lr;

    [HideInInspector]
    public int currentDiamond;
    [SerializeField] private Text currentDiamondText; 

    void Start()
    {
        lr = this.GetComponent<LineRenderer>();
        rb = this.GetComponent<Rigidbody2D>();
        animator = this.GetComponent<Animator>();
        lr.enabled = false;
        explosionPoint = this.transform.GetChild(1).transform;
        currentDiamond = 0;
    }

    void Update() {

        if (maxHealth <= 0) {
            Die();
        }

        if (Vector2.Distance(transform.position, Camera.main.transform.position) >= 9.9f) {
            Die();
        }

        if (transform.position.y <= -3f) {
            Die();
        }

        for (int i  = 0;  i  < hearts.Length; i ++)
        {
            if (i < maxHealth) {
                hearts[i].enabled = true;
            }
            else {
                hearts[i].enabled = false;
            }
        }

        moveSpeed += acceleration * Time.deltaTime;
        transform.Translate(new Vector2(1f, 0f) * Time.deltaTime * moveSpeed);

        if (Input.GetKey(KeyCode.Space) && jump == true) {
            Jump();
            jump = false;
            AudioManager.instance.PlaySound("Jump");
        }

        if (Input.GetMouseButtonDown(0)){
            AudioManager.instance.PlaySound("Shoot");
            StartCoroutine(Shoot());
        }
    }

    IEnumerator Shoot() {
        lr.enabled = true;
        RaycastHit2D hit = Physics2D.Raycast(shootPoint.position, shootPoint.right, distance, targetLayer);
        lr.SetPosition(0, shootPoint.position);
        if (hit) {
            lr.SetPosition(1, hit.point);
            if (hit.transform.GetComponent<Enemy>() != null) {
                GameObject temp = Instantiate(hitEffectPrefab, hit.point, Quaternion.identity);
                Destroy(temp, .51f);
                CameraShake.instance.Shake();
                hit.transform.GetComponent<Enemy>().TakeDamage(1);
            }
        }
        else {
            lr.SetPosition(1, shootPoint.position + shootPoint.right * distance);
        }
        yield return null;
        lr.enabled = false;
    }

    void Jump() {
        Vector2 velocity = rb.velocity;
        velocity.y = jumpHeight;
        rb.velocity = velocity;
        animator.SetBool("Jump", true);
    }

    public void PlayerTakeDamage(int damage){
        if (maxHealth <= 0) {
            return;
        }
        else {
            maxHealth -= damage;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground") {
            jump = true;
            animator.SetBool("Jump", false);
        }

        if (collision.gameObject.CompareTag("Trap")) {
            Die();
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Box") {
            FindObjectOfType<GroundSpawner>().SpawnGround();
        }

        if (other.gameObject.CompareTag("Diamond")) {
            currentDiamond += 1;
            AudioManager.instance.PlaySound("Collect");
            currentDiamondText.text = currentDiamond.ToString();
            other.gameObject.GetComponent<Animator>().SetTrigger("Collected");
            Destroy(other.gameObject, .101f);
        }

        if (other.gameObject.CompareTag("Heart")) {
            if (maxHealth >= 5) {
                return;
            }
            else {
                maxHealth += 1;
                AudioManager.instance.PlaySound("Collect");
                other.gameObject.GetComponent<Animator>().SetTrigger("Collected");
                Destroy(other.gameObject, .101f);
            }
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (GameManager.instance.isGameActive == false) {
            return;
        }
        else
        {
            if (collision.gameObject.tag == "Box")
            {
                Destroy(collision.gameObject, 5f);
            }
        }
    }

    void Die() {
        Debug.Log(this.transform.name + " Died.");
        gameOverUI.SetActive(true);
        CameraShake.instance.Shake();
        AudioManager.instance.PlaySound("Explosion");
        GameObject tempExplosion = Instantiate(explosionPrefab, explosionPoint.position, Quaternion.identity);
        Destroy(tempExplosion, .9f);
        GameManager.instance.isGameActive = false;
        Destroy(this.gameObject);
    }
}
